package com.leetcode.partition10;

/**
 * @author `RKC`
 * @date 2021/10/27 18:10
 */
public class LC990等式方程的可满足性 {

    public static boolean equationsPossible(String[] equations) {
        UnionFind unionFind = new UnionFind(26);
        for (String equation : equations) {
            char var1 = equation.charAt(0), var2 = equation.charAt(equation.length() - 1);
            if (equation.charAt(1) == '=') {
                unionFind.union(var1 - 'a', var2 - 'a');
            }
        }
        for (String equation : equations) {
            //如果本该不相等的两个变量，此时相等，就说明产生了冲突，
            int id1 = equation.charAt(0) - 'a', id2 = equation.charAt(equation.length() - 1) - 'a';
            if (equation.charAt(1) == '!' && unionFind.isConnected(id1, id2)) {
                return false;
            }
        }
        return true;
    }

    private static class UnionFind {

        private int[] ancestor;

        public UnionFind(int size) {
            ancestor = new int[size];
            for (int i = 0; i < size; i++) {
                ancestor[i] = i;
            }
        }

        public void union(int x, int y) {
            int parentX = find(x), parentY = find(y);
            if (parentX != parentY) {
                ancestor[parentY] = parentX;
            }
        }

        public int find(int x) {
            if (x == ancestor[x]) return x;
            ancestor[x] = find(ancestor[x]);
            return ancestor[x];
        }

        public boolean isConnected(int x, int y) {
            return find(x) == find(y);
        }
    }
}
